﻿
selectedText = "";
selectedTextArea = null;
function getSelectedText(id) {
    var range = $('textarea#' + id).getSelection();
    var st = range.text;
    return st;
}
var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = '../Profile/Login';
}
var alertInstance = new Object();
var arrCurrentCountry = new Array(); // current selected country
var arrMessagesFlows = new Array();
var arrKeywordValue = new Array();
$(document).ready(function () {
    $('.cus_textarea').corner('5px');
    $("#btn_new_audience").css("cursor", "pointer");
    $("#btn_new_audience").click(function () {
        if ($("#txtNewAudience").val() != "" && $("#txtNewDescription").val() != "") {
            var audience = new Object();
            audience.name = $("#txtNewAudience").val();
            audience.description = $("#txtNewDescription").val();
            audience.campaignid = $("#campaign_selection").find("option:selected").attr("id"); ;
            audience.audiencelevel = "2";
            $.ajax({
                url: gb_servicePath + "/group/create.json",
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(audience),
                "dataType": 'json',
                success: function (data) {
                    var o = $("<option selected='selected' id='" + data.ReturnData.ID + "' value='" + data.ReturnData.Name + "' >" + data.ReturnData.Name + "</option>");
                    $("#audience_selection").find(".customStyleSelectBoxInner").html(data.ReturnData.Name);
                    $("#audience_selection").find("select").append(o);
                    $("#txtNewAudience").val("");
                    $("#txtNewDescription").val("");
                },
                error: function (jqXHR, textStatus) {
                    if (isBug) {
                        alert("Error in GEMAPI/keyword/create.json");
                    }
                }
            });
        }
    });

    $('#sl_campaign').change(function () {
        getListAudience(true);
    });
});

// Get all countries
function getCountries() {
   // arrCountry.length = 0;
 $("#list_countries .list_count").css("display", "none");
 $.ajax({ url: gb_servicePath + '/campaign/ID/' + $("#sl_campaign").find(":selected").attr("id") + '.json',
     dataType: 'json',
     async: false,
     success: function (json1) {
         var data = json1.ReturnData;
         for (i = 0; i < data.Countrys.length; i++) {
             $("#country" + data.Countrys[i].Id.toString()).css("display","block");
         }
     }
 });
}

// Edit keyword
function editKeyword(id, KeyworkVal) {
    $('#make_keyword_alert .header_box_campain').html('Edit Keyword');
    $('#make_keyword_alert').attr("keyWordId", id);
    $('#make_keyword_alert').jqmShow();
    $('#make_keyword_alert').find(".countable").val("");
    $('#errorMakekeyword').html("");
    $("#txtKeywordOptOut").val("")
    $('#make_keyword_alert div#keyword').hide();
    $('#txtKeyword').show();
    $('#txtKeyword').val("");
    $('.cus_input').css("display", "inline-block");
    $("#B1").parent().parent().next().css("display", "none");
    $("#B1").parent().parent().next().next().css("display", "none");
    $("#B1").parent().parent().css("display", "none");
    $("#btnSaveKeyWord .cus_button_mid").text("Update");
    $.getJSON(gb_servicePath + '/keyword/ID/' + id + '.json', {},
                function (json2) {
                    if (json2.StatusCode == 200) {
                        var data = json2.ReturnData;
                        for (i = 0; i < data.FollowUpMessageFlowList.length; i++) {
                            $("#messagestype" + data.FollowUpMessageFlowList[i].MessageflowType.Id.toString() + " textarea").val(data.FollowUpMessageFlowList[i].Messagebody);

                        }
                        $('#make_keyword_alert').attr("keywordname", data.Name);
                        $('#make_keyword_alert').attr("compid", data.Component.Id);
                        if (data.Component.Id == "6") {
                            $("#txtKeywordOptIn").parent().parent().html(data.Name);
                            $(".opt-Out").css("display", "none");
                            $(".opt-Out").prev().css("display", "none");
                            $(".opt-In").css("display", "block");
                            $(".opt-In").prev().css("display", "block");
                        }
                        else {
                            $("#txtKeywordOptOut").parent().parent().html(data.Name);
                            $(".opt-Out").css("display", "block");
                            $(".opt-Out").prev().css("display", "block");
                            $(".opt-In").css("display", "none");
                            $(".opt-In").prev().css("display", "none");
                        }

                        $('#make_keyword_alert').jqmShow();
                    }
                });
}
function addKeyword(id, messflowid) {
    $('#make_keyword_alert .header_box_campain').html('Make Keyword');
    $('#btnSaveKeyWord').removeClass('update_key');
    $('#tbl_new_userOptIn, #lbl_opt_in, #tr_key_opt_in, .opt-Out, #lbl_opt_out').removeClass('hide');

    selectedTextArea = $('textarea#make_keyword' + id); //.replaceSelection('<' + selectedText + '>', true);
    $('#make_keyword_alert').attr("messflowid", messflowid);
    $('#make_keyword_alert').jqmShow();
    $('#make_keyword_alert').find(".countable").val("");
    $('#errorMakekeyword').html("");
    $("#txtKeywordOptIn").val("");
    $("#txtKeywordOptOut").val("");
    if (selectedText != "") {
        $('#make_keyword_alert div#keyword').show();
        $('#txtKeyword').hide();

        $('#make_keyword_alert div#keyword').html(selectedText);
        $('#make_keyword_alert.cus_input').css("display", "none");
    }
    else {
        $('#make_keyword_alert div#keyword').hide();
        $('#txtKeyword').show();
        $('#txtKeyword').val("");
        $('.cus_input').css("display", "inline-block");

    }
}

//function getURLParameter(name) {
//    //alert(name.toUpperCase() + '-' + location.toUpperCase());
//    return decodeURI(
//                (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
//                );
//}
$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});

function getListCampain() {
    $.getJSON(gb_servicePath + '/campaign/list/summary.json?userid=' + userId,
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                                $("#campaign_selection").find(".customStyleSelectBoxInner").html(val.Name);
                            } else {
                                var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                            }

                            $("#campaign_selection").find("select").append(o);
                        });
                        if (getURLParameter("id").toString() == "null") {
                            getListAudience(true);
                        }
                    }
                });
}


function getListFunction() {
    $.getJSON(gb_servicePath + '/Component/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                                $("#campaign_selection").find(".customStyleSelectBoxInner").html(val.Name);
                            } else {
                                var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                            }

                            $("#campaign_selection").find("select").append(o);
                        });
                    }
                });
}
function getListMessagesType() {
    $.getJSON(gb_servicePath + '/component/list.json?productname=Common',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (val.Id == 6 || val.Id == 7) {
                                for (var i = 0; i < val.MessageflowType.length; i++) {
                                    var o = $("#messflows_temp").clone();
                                    $(o).attr("id", "messagestype" + val.MessageflowType[i].Id);
                                    $(o).attr("value", val.MessageflowType[i].Id);
                                    $(o).addClass("messagesflowtype");
                                    $(o).css("display", "block");
                                    $(o).find("b").html("Message for " + val.MessageflowType[i].Name);
                                    if (val.Id == 6) {
                                        $("#tbl_new_userOptIn").find("ul").append(o);
                                    }
                                    if (val.Id == 7) {
                                        $("#tbl_new_userOptOut").find("ul").append(o);
                                    }
                                }
                            }
                        });
                    }
                });
}
//Bind data to Target Audience
function getListAudience(wait) {
    $("#btn_target_audience_template").css("display", "none");
    $("#btn_target_audience_template_2").css("display", "none");

    $.ajax({ url: gb_servicePath + '/group/list.json?userid=' + userId + "&campaignid=" + $("#campaign_selection").find("option:selected").attr("id"),
        dataType: 'json',
        data: '',
        async: wait,
        success: function (json1) {
            if (json1.StatusCode == 200) {

                $("#countries0 #list_audience").find(".list_count").each(function () {
                    if ($(this).attr("id") != "btn_target_audience_template") {
                        $(this).remove();
                    }
                });

                $.each(json1.ReturnData, function (i, val) {
                    var o = $("#btn_target_audience_template").clone();
                    $(o).css("display", "block");
                    $(o).find("input").attr("value", val.Name);
                    $(o).attr("id", val.ID);
                    $(o).find("span").html(val.Name);
                    if ($("#countries0 #list_audience").find(".jspPane").length > 0) {
                        $("#countries0 #list_audience").find(".jspPane").append(o);
                    } else {
                        $("#countries0 #list_audience").append(o);
                    }
                    var oo = $("#btn_target_audience_template_2").clone();
                    $(oo).css("display", "block");
                    $(oo).find("input").attr("value", val.Name);
                    $(oo).attr("id", 'c_' + val.ID);
                    $(oo).attr("value", val.ID);
                    $(oo).find("span").html(val.Name);
                    $("#list_audience_make_keyword").find(".jspPane").append(oo);

                    if (i == 0) {
                        var o = $("<option selected='selected' id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
                        $("#audience_selection").find(".customStyleSelectBoxInner").html(val.Name);
                    } else {
                        var o = $("<option id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
                    }

                    $("#audience_selection").find("select").append(o);

                });
                $('.label_check, .label_radio, .label_check_ip').click(function () {
                    setupLabel();
                });
                $('#countries0 #list_audience').jScrollPane();

            }
        }
    });
}
function format2Digi(num) {
    if (num > 9) return num
    else return "0" + num;
}
function getKeywordById(kwid) {
    $.getJSON(gb_servicePath + '/keyword/ID/' + kwid + '.json', {},
                function (json2) {
                    if (json2.StatusCode == 200) {
                        var data = json2.ReturnData;
                        arrKeywordValue[data.Id + "_"] = data;
                    }
                });
}
//get instance of alert and bind data for edit
function getAlertInstance(id) {
    $.getJSON(gb_servicePath + '/alertinstance/ID/' + id + '.json',
                    {}, function (json) {
                        if (json.StatusCode == 200) {
                            var data = json.ReturnData;
                            if (data == null) {
                                if (isBug) {
                                    alert("Wrong alert id");
                                }
                                return;
                            }
                            alertInstance.Id = data.Alertcollection.Id;
                            // campaing
                            $("#campaign_selection").find("option").each(function (i) {
                                if ($(this).attr("id") == data.Alertcollection.Campaign.Id) {
                                    alertInstance.campaignId = data.Alertcollection.Campaign.Id;
                                    $(this).attr("selected", "selected");
                                    $("#campaign_selection").find(".customStyleSelectBoxInner").html($(this).attr("value"));
                                }
                            });
                            if (location.hash == "#copy") {
                                $('#txtName').val('');
                            }
                            else {
                                $("#txtName").val(data.Alertcollection.Name);
                                $("#sl_campaign").css('display', 'none');
                                $("#sl_campaign").next().css('display', 'none');
                                $("#sl_campaign").after('<strong id="ddlCampAdd">' + $("#sl_campaign").find(":selected").text() + '</strong>');
                            }
                            getListAudience(false);
                            //isactive 
                            if (data.Alertcollection.IsActive == 1) {
                                $('label.label_check_ip input#chkActive').attr('checked', 'checked');
                                $(".label_check_ip").addClass("c_ip_on");
                            } else {
                                $('label.label_check_ip input#chkActive').removeAttr('checked');
                                $(".label_check_ip").removeClass("c_ip_on");
                            }
                            //audience
                            var strAudience = "";
                            $.each(data.Alertcollection.Audience, function (i, val) {
                                strAudience += val.ID + ",";
                            });
                            // alert("str audience : " + strAudience);
                            $("#list_audience").find(".list_count").each(function (index) {
                                if (strAudience == "" && index == 0) {
                                    $(this).find(".label_check").addClass("c_on");
                                    $(this).find(".label_check input").attr('checked', true);
                                }
                                if (strAudience.indexOf($(this).attr("id")) >= 0) {
                                    $(this).find(".label_check").addClass("c_on");
                                    $(this).find(".label_check input").attr('checked', true);
                                }
                            });
                            console.log("str Audience:" + strAudience);

                            //                            var start_time = data.Alertcollection.StartTime.substr(6).replace(')', '').replace('/', '');
                            //                            var end_time = data.Alertcollection.EndTime.substr(6).replace(')', '').replace('/', '');
                            //                            //alert(parseInt(date));05/01/2011 15:36
                            //                            start_time = new Date(parseInt(start_time));
                            //                            // start_time = format2Digi(start_time.getDay()) + '/' + format2Digi(start_time.getMonth()) + '/' + start_time.getFullYear() + ' ' + format2Digi(start_time.getHours()) + ':' + format2Digi(start_time.getMinutes());
                            //                            end_time = new Date(parseInt(end_time));
                            //                            // end_time = format2Digi(end_time.getDay()) + '/' + format2Digi(end_time.getMonth()) + '/' + end_time.getFullYear() + ' ' + format2Digi(end_time.getHours()) + ':' + format2Digi(end_time.getMinutes());
                            var start_time = data.AlertInstanceSummary.AlertCollectionSummary.StartTime.substr(6).replace(')', '').replace('/', '');
                            var end_time = data.AlertInstanceSummary.AlertCollectionSummary.EndTime.substr(6).replace(')', '').replace('/', '');
                            //alert(parseInt(date));05/01/2011 15:36
                            start_time = new Date(parseInt(start_time));
                            end_time = new Date(parseInt(end_time));
                            // end_time = format2Digi(end_time.getDay()) + '/' + format2Digi(end_time.getMonth()) + '/' + end_time.getFullYear() + ' ' + format2Digi(end_time.getHours()) + ':' + format2Digi(end_time.getMinutes());
                            $("#start_date").val(format2Digi(start_time.getUTCMonth() + 1) + '/' + format2Digi(start_time.getUTCDate()) + '/' + start_time.getUTCFullYear());
                            $("#end_date").val(format2Digi(end_time.getUTCMonth() + 1) + '/' + format2Digi(end_time.getUTCDate()) + '/' + end_time.getUTCFullYear());
                            $("#start_time").val(format2Digi(start_time.getUTCHours()) + ':' + format2Digi(start_time.getUTCMinutes()));
                            $("#end_time").val(format2Digi(end_time.getUTCHours()) + ':' + format2Digi(end_time.getUTCMinutes()));

                            var frequency = "";
                            if (data.Alertcollection.AlertCollectionSummary.FrequencySettings.length > 0) {
                                var Timeunitid = data.Alertcollection.AlertCollectionSummary.FrequencySettings[0].Timeunitid;

                                switch (Timeunitid) {
                                    case 1:
                                        frequency = "Minute";
                                        $("#ddlrecurring").val("None");
                                        break;
                                    case 2:
                                        frequency = "Hour";
                                        $("#ddlrecurring").val("Occurs each hour on these minutes");
                                        for (var i = 1; i < data.AlertCollectionSummary.FrequencySettings.length; i++) {
                                            addMinute(data.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue.toString());
                                        }
                                        break;
                                    case 3:
                                        frequency = "Day";
                                        $("#ddlrecurring").val("Occurs each day at these times");
                                        var arrH = new Array();
                                        var arrM = new Array();
                                        for (var i = 1; i < data.Alertcollection.AlertCollectionSummary.FrequencySettings.length; i++) {
                                            if (data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitid.toString() == "2") {
                                                arrH.push(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue.toString());
                                            }
                                            /* if (data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitid.toString() == "1") {
                                            arrM.push(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue.toString());
                                            }*/
                                        }
                                        for (var i = 0; i < arrH.length; i++) {
                                            /*if (arrM[i] != undefined) {
                                            addHour(arrH[i] + ":" + arrM[i]);
                                            } else {
                                            addHour(arrH[i] + ":");
                                            }*/
                                            addHour(arrH[i] + ": 00");
                                        }
                                        break;
                                    case 4:
                                        frequency = "Week";
                                        $("#ddlrecurring").val("Occurs each week on these days");
                                        for (var i = 1; i < data.Alertcollection.AlertCollectionSummary.FrequencySettings.length; i++) {
                                            addDay(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue.toString());
                                        }
                                        break;
                                    case 5:
                                        frequency = "Month";
                                        $("#ddlrecurring").val("Occurs each month on these days");
                                        for (var i = 1; i < data.Alertcollection.AlertCollectionSummary.FrequencySettings.length; i++) {
                                            addDay(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue.toString());
                                        }
                                        break;
                                    case 6:
                                        frequency = "Year";
                                        $("#ddlrecurring").val("Occurs every year on these dates");
                                        var arrD = new Array();
                                        var arrM = new Array();
                                        for (var i = 1; i < data.Alertcollection.AlertCollectionSummary.FrequencySettings.length; i++) {
                                            if (data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitid.toString() == "3") {
                                                arrD.push(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue);
                                            }
                                            if (data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitid.toString() == "5") {
                                                arrM.push(data.Alertcollection.AlertCollectionSummary.FrequencySettings[i].Timeunitvalue);
                                            }
                                        }
                                        for (var i = 0; i < arrH.length; i++) {
                                            addHour(arrD[i] + "/" + arrM[i]);
                                        }
                                        break;
                                }
                            } else {
                                frequency = "none";
                                $("#ddlrecurring").val("None");
                            }
                            $("#ddlrecurring").trigger("change");


                            // if (data.AlertInstanceSummary.MessageFlows.length > 0) {
                            $.each(data.AlertInstanceSummary.MessageFlows, function (i, val) {
                                var oMess = new Object();
                                oMess.Id = val.Id;
                                oMess.countryId = val.Country.Id;
                                oMess.mediaId = val.Media.Id;
                                oMess.languageId = val.Language.Id;
                                oMess.messagesBody = val.Messagebody;
                                oMess.messageflowType = { Id: val.MessageflowType.Id, Name: val.MessageflowType.Name };
                                // oMess.Name = val.Name;
                                oMess.keywordlist = val.KeywordIDList;
                                var keywordvalues = new Array();
                                oMess.keywordvalues = keywordvalues;
                                arrMessagesFlows[oMess.countryId + "_" + oMess.languageId + "_" + oMess.mediaId] = oMess;
                                for (var k = 0; k < oMess.keywordlist.length; k++) {
                                    getKeywordById(oMess.keywordlist[k]);
                                }
                            })
                            //}

                            var country = "";
                            var delivery = "";
                            var arrCountry = new Array();
                            $.each(data.Alertcollection.Preference, function (i, val) {
                                country += val.Preference.Country.Name + " ( " + val.Preference.Language.Name + " ) " + "<br/>"
                                delivery += val.Media.Name;
                                //find exist country
                                var o = new Object();
                                var needInsert = true;
                                for (var i = 0; i < arrCountry.length; i++) {
                                    if (arrCountry[i].Country.Id == val.Preference.Country.Id) {
                                        o = arrCountry[i];
                                        needInsert = false;
                                        break;
                                    }
                                }
                                if (needInsert) {
                                    var cont = new Object();
                                    cont.Id = val.Preference.Country.Id;
                                    cont.Name = val.Preference.Country.Name;
                                    o.Country = cont;
                                }

                                var timezone = new Object();
                                timezone.Id = val.Preference.Timezone.Id;
                                timezone.Name = val.Preference.Timezone.Name.split(")")[0] + ")"; ;
                                o.Timezone = timezone;

                                var languages = new Array();
                                if (!needInsert) {
                                    languages = o.Language;
                                }

                                var oLang = new Object();
                                var medias = new Array();
                                for (var i = 0; i < languages.length; i++) {
                                    if (languages[i].Id == val.Preference.Language.Id) {
                                        medias = languages[i].Media;
                                        oLang = languages[i];
                                    }
                                }

                                if (medias.length == 0) {
                                    //insert new languages
                                    oLang.Id = val.Preference.Language.Id;
                                    oLang.Name = val.Preference.Language.Name;
                                    oLang.selected = true;
                                    oLang.CountryPreId = val.Preference.Id;
                                    languages.push(oLang);
                                }
                                //search for media 
                                var omedia = new Object();
                                omedia.Id = val.Media.Id;
                                omedia.Name = val.Media.Name;
                                omedia.selected = true;

                                var needInsertMedia = true;
                                for (var i = 0; i < medias.length; i++) {
                                    if (medias[i].Id == omedia.Id) {
                                        needInsertMedia = false;
                                        break;
                                    }
                                }
                                if (needInsertMedia) {
                                    medias.push(omedia);
                                }
                                oLang.Media = medias;
                                if (needInsert) {
                                    o.Language = languages;
                                    arrCountry.push(o);
                                }

                            })

                            for (var i = 0; i < arrCountry.length; i++) {
                                addCountryPre(arrCountry[i]);
                            }
                        } else {
                            // alert("Wrong alert Id");
                        }
                    }
                );
}


function addMinute(str) {
    $('#minutes').append('<span class="icon_remove">:' + str + '</span>');
    $(".icon_remove").click(function () {
        $(this).remove();
    });
}

//add hour by click 
function addHour(str) {
    $('#hours').append('<span class="icon_remove">' + str + '</span>');
    $(".icon_remove").click(function () {
        $(this).remove();
    });
}

//add day by click or bind data when edit
function addDay(str) {
    $('#list_days').append('<span class="icon_remove">' + str + '</span>');
    $(".icon_remove").click(function () {
        $(this).remove();
    });
}


//add date by click or bind data when edit
function addDateFrequency(str) {
    $('#list_dates').append('<span class="icon_remove">' + str + '</span>');
    $(".icon_remove").click(function () {
        $(this).remove();
    });
}

//add country in list country 
function addCountryPre(o) {
    o.CountryName = o.Country.Name;
    arrCurrentCountry.push(o);
    if ($("#country_Item" + o.Country.Id).length > 0) {
        $("#country_Item" + o.Country.Id).remove();
    }
    var oCoun = $("#country_temp").clone();
    $(oCoun).attr("data", JSON.stringify(o));
    $(oCoun).find(".col_country").html(o.Country.Name);
    $(oCoun).attr("id", "country_Item" + o.Country.Id);
    $(oCoun).attr("value", o.Country.Id);
    $(oCoun).css("display", "block");

    for (var i = 0; i < o.Language.length; i++) {
        if (o.Language[i].selected == true) {
            if (i % 2 == 1) {
                var olang = $("<div value='" + o.Language[i].Id + "' class='alt'>" + o.Language[i].Name + "</div>");
                $(oCoun).find(".col_language").append(olang);
            } else {
                var olang = $("<div value='" + o.Language[i].Id + "'>" + o.Language[i].Name + "</div>");
                $(oCoun).find(".col_language").append(olang);
            }
            var arrMedias = o.Language[i].Media;
            var strmedia = "";
            var strmediaid = "";
            for (var j = 0; j < arrMedias.length; j++) {
                if (arrMedias[j].selected == true) {
                    strmedia += arrMedias[j].Name + ", ";
                    strmediaid += arrMedias[j].Id;
                }
            }

            if (strmedia.substring(strmedia.length - 2, strmedia.length) == ", ") {
                strmedia = strmedia.substring(0, strmedia.length - 2);
            }
            var omedia;
            if (i % 2 == 1) {
                omedia = $("<div value='" + strmediaid + "' class='alt'>" + strmedia + "</div>");
            } else {
                omedia = $("<div value='" + strmediaid + "'>" + strmedia + "</div>");
            }
            $(oCoun).find(".col_method").append(omedia);
        }
    }
    var ohide = $("<div class='hide row_hide'>&nbsp;</div>")
    $(oCoun).find(".col_language").append(ohide);
    var ohidemedia = $("<div class='hide row_hide'><a href='#messages' class='i_delete'>Delete</a></div>");
    $(oCoun).find(".col_method").append(ohidemedia);

    $("#listCountries").find(".jspPane").append(oCoun);

    refreshScrollbarListCountry();

    $('.list_row').jScrollPane({ animateScroll: true });

    $(oCoun).click(function () {
        $('#messages').removeClass('hide');
        $("#box_select_countries").css("display", "none");
        $('.rows').removeClass('hover');
        $(this).addClass('hover');
        $('.row_hide').addClass('hide');
        $(this).find('.row_hide').removeClass('hide');
        $('.col_method').css('width', '105px');
        $('.list_row').jScrollPane({ animateScroll: true });
        //  alert(jQuery.parseJSON($(this).attr("data")).Country.Name);
        //remove all old $(".mess_detail")
        $("#messflows").find(".mess_detail").each(function () {
            if ($(this).attr("id") != "mess_detail_temp") {
                $(this).remove();
            }
        });
        //remove all .counttable
        $(".jqEasyCounterMsg").remove();
        var o = jQuery.parseJSON($(this).attr("data"));
        addMessagesflow(o);
        $('.countable').jqEasyCounter({
            'maxChars': 500,
            'maxCharsWarning': 161,
            'msgFontSize': '11px',
            'msgFontColor': '#595959',
            'msgTextAlign': 'right',
            'msgWarningColor': '#F00',
            'msgAppendMethod': 'insertBefore'
        });
        $('.jqEasyCounterMsg').corner();

        $('#messflows textarea.countable').mouseup(function () {
            var id = $(this).attr('id');
            selectedText = getSelectedText(id);
        });

        $('#Span3').click(function () {
            if (selectedTextArea && selectedText != '') selectedTextArea.replaceSelection('<' + selectedText + '>', true);
           // $('#make_keyword').jqmHide();
        });

    });

    $(".i_delete").click(function () {
        $("#box_confirm").jqmShow();
    });
}

//recalculate height of list country
function refreshScrollbarListCountry() {
    if ($('.rows').length == 2) {
        $('div#listCountries div.jspContainer').css('height', '63px');
    }
    else if ($('.rows').length == 3) {
        $('div#listCountries div.jspContainer').css('height', '123px');
    }
    else if ($('.rows').length == 4) {
        $('div#listCountries div.jspContainer').css('height', '183px');
    } else if ($('.rows').length < 2) {
        $('div#listCountries div.jspContainer').css('height', '0px');
    }
    if ($('.rows').length > 3) {
        $('.col_method').css('width', '105px');

    }
    else {
        $('.col_method').css('width', '106px');
    }
}

// add messages flows to messages box
function addMessagesflow(ob) {
    for (var j = 0; j < ob.Language.length; j++) {
        var medias = ob.Language[j].Media;
        if (ob.Language[j].selected == true) {
            for (var i = 0; i < medias.length; i++) {
                if (medias[i].selected == true) {
                    var o = $("#mess_detail_temp").clone();
                    $(o).find(".mess_detail_txt").html(ob.Country.Name + "," + ob.Language[j].Name + "," + medias[i].Name);
                    $(o).attr("id", "mess_detail_" + ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id);
                    $(o).attr("messflowid", ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id);
                    $(o).css("display", "block");
                    $(o).attr("value", j + "_" + i);
                    $(o).find("textarea").attr("id", "txt_" + j + "_" + i);
                    //alert("messages flows : " + arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id].messagesBody);
                    $("#messflows").find(".jspPane").append(o);
                    if (arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id] != undefined) {
                        var obb = arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id];
                        $(o).find("textarea").attr("instanceid", obb.Id);
                        // edit alert or create new alert with
                        $(o).find("textarea").val(obb.messagesBody);
                        var keywordidlist = "";
                        for (var k = 0; k < obb.keywordlist.length; k++) {
                            keywordidlist += obb.keywordlist[k];
                            if (obb.keywordvalues[k] != undefined) {
                                var oK = $("#btKeywordTemp").clone();
                                $(oK).find(".btparent").removeClass("with_close");
                                $(oK).find(".btparent").addClass("key_disable");
                                $(oK).find(".key_button_mid").click(function () {
                                    if(!$(this).parent().hasClass("key_disable"))
                                    editKeyword($(this).parent().parent().attr("value")); 
                                });
                                $(oK).attr("value", obb.keywordlist[k]);
                                $(oK).find(".key_button_mid").html(obb.keywordvalues[k]);
                                //$(oK).find(".key_button_mid").attr("id", obb.keywordlist[k]);
                                $(oK).css("display", "block");
                                $(oK).attr("id", "btKeyword" + obb.keywordlist[k]);
                                $(o).find(".keywordcollection").append(oK);
                                $(o).find(".key_button_right").attr("thismessID",obb.Id);
                                $(oK).find(".key_button_right").click(function () {
                                    if (!$(this).parent().hasClass("key_disable")) {
                                        removeKeyword($(this).parent().parent().attr("value"), userId, $(this).attr("thismessID"));
                                        $(this).parent().parent().remove();
                                    }
                                });
                            } else if (arrKeywordValue[obb.keywordlist[k] + "_"] != undefined) {
                                var oK = $("#btKeywordTemp").clone();
                                $(oK).find(".btparent").removeClass("with_close");
                                $(oK).find(".btparent").addClass("key_disable");
                                $(oK).attr("value", obb.keywordlist[k]);
                                $(oK).find(".key_button_mid").html(arrKeywordValue[obb.keywordlist[k] + "_"].Name);
                                $(oK).find(".key_button_mid").click(function () {  if (!$(this).parent().hasClass("key_disable")) { editKeyword($(this).parent().parent().attr("value")); } });
                                $(oK).css("display", "block");
                                $(oK).attr("id", "btKeyword" + obb.keywordlist[k]);
                                $(o).find(".keywordcollection").append(oK);
                                $(o).find(".key_button_right").attr("thismessID", obb.Id);
                                $(oK).find(".key_button_right").click(function () {
                                    if (!$(this).parent().hasClass("key_disable")) {
                                        
                                        removeKeyword($(this).parent().parent().attr("value"), userId, $(this).attr("thismessID"));
                                        $(this).parent().parent().remove();
                                    }
                                });
                            }
                        }

                    }
                    $(o).attr("keywordidlist", keywordidlist);
                    //                                $(".key_button_mid").click(function () {
                    //                                    var idkeyword = $(this).attr("id");
                    //                                    alert(idkeyword);
                    //                                });
                }
            }
        }

    }

    $(".make_keyword").css("cursor", "pointer");
    $(".make_keyword").click(function () {
        if (!$(this).hasClass("edit_disable")) {
            addKeyword($(this).parent().attr("value"), $(this).parent().attr("messflowid"));
        }
    });

    $('#make_keyword_alert').jqm({modal:true});
    //$('#make_keyword_alert').removeClass('hide');
    $('#comfirm_blk').jqm();
    $('#comfirm_blk').jqmAddClose($('#confirm_cancel'));
    $('#make_keyword_alert').css('left', ($(window).width() - 390) / 2);
    $("#box_alert").jqm();

    $('#box_confirm').jqm({ trigger: '.i_delete' });
    $('#box_confirm2').jqm({ trigger: '.btn_delete' });
    $('#box_confirm2').jqmAddClose($('#btnCancel_confirm2'));
    $('#make_keyword_alert').jqmAddClose($('.btn_Close'));
    $('#make_keyword_alert').jqmAddClose($('.btn_Cancel'));
    //  $('#make_keyword_alert').jqmAddClose($('.btn_Save'));
    $('#box_alert').jqmAddClose($('#btnOk_boxalert'));
    $('#box_confirm').jqmAddClose($('#btnCancel_confirm1'));
    $("#messflows").jScrollPane({ animateScroll: true });
    if ($(".mess_detail").length > 4) {
        $(".mess_detail").css("padding-right", '5px');
    }
    else {
        $(".mess_detail").css("padding-right", '15px');
    }

    $('#btn_Edit').click(function () {
        //$('.make_keyword').attr('href', '#make_keyword');
        $('.edit_disable').css('display', 'none');
        $('.edit_enable').css('display', 'block');
        $('.mess_detail textarea').removeAttr('disabled');
        $('.mess_detail textarea').addClass('textarea_enable');
       // $('a.btn_delete').css('visibility', 'visible');
        $('#btn_SaveMessage').removeClass('hide');
        $('#btn_Cancel').removeClass('hide');
        $(this).addClass('hide');
        $('.itemfilter').hide();
        $('.btn_unleashed').show();
        $('.btn_freetix').show();
        $(".btparent").removeClass("key_disable");
        $(".btparent").addClass("with_close");
        $('#btn_Cancel').click(function () {
            $.fancybox.close();
        });
    });
}

function sortCountryTable(isDec) {
    if (isDec) {
        $("#btSortCountry").attr("sort", "-1");
        $("#btSortCountry").find("img").rotate(0);
        var arr = arrCurrentCountry.objSort("CountryName", -1);
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                $(this).remove();
            }
        });
        arrCurrentCountry = new Array();
        for (var i = 0; i < arr.length; i++) {
            addCountryPre(arr[i]);
        }
    } else {
        $("#btSortCountry").attr("sort", "1");
        $("#btSortCountry").find("img").rotate(180);
        var arr = arrCurrentCountry = arrCurrentCountry.objSort("CountryName", 1);
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                $(this).remove();
            }
        });
        arrCurrentCountry = new Array();
        for (var i = 0; i < arr.length; i++) {
            addCountryPre(arr[i]);
        }
    }

}
$(document).ready(function () {
    // getListAudience();
    getListCampain();
    getListMessagesType();
    if (getURLParameter("id").toString() != "null") {
        //edit mode
        //  alertInstance.Id = getURLParameter("id");
        getAlertInstance(getURLParameter("id"));
        if (location.hash == "#copy") {
            $('h1.title').html('New Alert');
            $("#btnSave").find(".cus_button_mid").html("Save");
        }
        else {
            $('h1.title').html('Edit Alert');
            $("#btnSave").find(".cus_button_mid").html("Update");
        }
    } else {
        $("#btnSave").find(".cus_button_mid").html("Save");
    }

    $("#start_date").change(function () {
        // check input ($(this).val()) for validity here
        $('#txt_day').val($(this).val().substring(3, 5));
        //$('#txt_mmdd').val($(this).val().substring(0, 5));
    });
    $("#start_time").change(function () {
        // check input ($(this).val()) for validity here
        //$('#txt_minute').val($(this).val().substring(3, 5));
        $('#txt_hour').val($(this).val());
    });


    $('#txt_mmdd').datetimeEntry({ datetimeFormat: 'O/D', spinnerImage: '' });
    $('.txt_time').datetimeEntry({ datetimeFormat: 'H:M', spinnerImage: '' });
    //$('#txt_minute').datetimeEntry({ datetimeFormat: 'M', spinnerImage: '' });
    $('.txt_date').datetimeEntry({ datetimeFormat: 'O/D/Y', spinnerImage: '' });
    $('#txt_day').datetimeEntry({ datetimeFormat: 'D', spinnerImage: '' });

    //remove country from list
    $('#btnOk_confirm1').click(function () {
        var divid = $("#listCountries").find(".hover").attr("id");
        var countryId = divid.substring(12, divid.length);
        //remove from arrCurrentCountry
        for (var i = 0; i < arrCurrentCountry.length; i++) {
            if (countryId = arrCurrentCountry[i].Country.Id) {
                arrCurrentCountry.splice(i, 1);
                break;
            }
        }
        $("#listCountries").find(".hover").remove();
        $('#box_confirm').jqmHide();

        $('.edit_disable').css('display', 'block');
        $('.edit_enable').css('display', 'none');
        $('.mess_detail textarea').attr('disabled', 'disabled');
        $('.mess_detail textarea').removeClass('textarea_enable');
        $('.itemfilter').show();
        $('.btn_unleashed').hide();
        $('.btn_freetix').hide();
        $('#btn_SaveMessage').addClass('hide');
        $('#btn_Cancel').addClass('hide');
        $('#btn_Edit').removeClass('hide');
        $(".btparent").addClass("disable");
        $(".btparent").removeClass("width_close");

        $('#messages').addClass('hide');
        $('.rows').removeClass('hover');
        $('.row_hide').addClass('hide');
        if ($('.rows').length > 3) {
            $('.col_method').css('width', '105px');
        }
        else {
            $('.col_method').css('width', '106px');
        }
        $('.list_row').jScrollPane({ animateScroll: true });

        refreshScrollbarListCountry();

    });

    $('#btnOk_confirm2').click(function () {
        $('div.selected').remove();
        $('#box_confirm2').jqmHide();
        //$('.scroll-pane').jScrollPane({ animateScroll: true });
    });

    $('.btn_delete').click(function () {
        $(this).parent().addClass('selected');
    });
    $('.btn_unleashed').click(function () {
        $(this).remove();
    });
    $('.btn_freetix').click(function () {
        $(this).remove();
    });

    $("#btSortCountry").find("img").rotate(180);
    $("#btSortCountry").click(function () {
        if ($(this).attr("sort").toString() == "1") {
            sortCountryTable(true);
        } else {
            sortCountryTable(false);
        }
    });

    // confirm box popup
    $('#comfirm_blk').jqm();
    $('#comfirm_blk').jqmAddClose($('#confirm_cancel'));

    //$('#make_keyword').css('right', ($(window).width() - 1100) / 2 + 120);
    $("#box_alert").jqm();

    $('#box_confirm').jqm({ trigger: '.i_delete' });
    $('#box_confirm2').jqm({ trigger: '.btn_delete' });
    $('#box_confirm2').jqmAddClose($('#btnCancel_confirm2'));
    $('#make_keyword_alert').jqmAddClose($('.btn_Close'));
    $('#make_keyword_alert').jqmAddClose($('.btn_Cancel'));
    //  $('#make_keyword_alert').jqmAddClose($('.btn_Save'));
    $('#box_alert').jqmAddClose($('#btnOk_boxalert'));
    $('#box_confirm').jqmAddClose($('#btnCancel_confirm1'));
    $('.test').jScrollPane({ animateScroll: true });
    $('.list_audience_scroll').jScrollPane({ animateScroll: true });

    //$('.list_row').jScrollPane().hide();

    $('.scroll-pane').jScrollPane({ animateScroll: true });
    $('.countries').hide();
    $('#btnAudience').click(function (event) {
        event.stopPropagation();
        if ($('#countries0').css('display') == 'none') {
            $('#countries0').show();
        } else {
            $('#countries0').hide();
        }
        $(document).click(function () {
            if ($('#countries0').css('display') != 'none') {
                $('#countries0').hide();
            }
        });
        $('#countries0').click(function (event) {
            event.stopPropagation();
        });


    });
    $("#checkall").click(function () {
        $('.case').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearall").click(function () {
        $('.case').removeAttr('checked');
        setupLabel();
    });
    //            $(".btn_delete").click(function () {
    //                alert('tét');
    //            });

    $(".txt_date").datepicker({
        showOn: "button",
        buttonImage: "../images/Controls/btn_ca.png",
        buttonImageOnly: true
    });

    $('body').addClass('has-js');

    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });

    setupLabel();

    $('select.select_long').customStyle();
    $('select.select_short').customStyle();

    $("#btn_AddCountries").click(function () {
        $("#sl_campaign").attr('disabled', 'disabled');
        $('#rowCountries table').css('border', 'none');
        $('#rowCountries .lang').css('color', '#595959');
        $('#rowCountries .method').css('color', '#595959');
        if ($("#box_select_countries").css("display") == "none") {
            $("#list_countries").find(".label_check").removeClass("c_on");
            getCountries();
            for (var i = 0; i < arrCurrentCountry.length; i++) {
                addCountryItemDisplay(arrCurrentCountry[i], false);
                $("#country" + arrCurrentCountry[i].Country.Id).find(".label_check").addClass("c_on");
                $("#country" + arrCurrentCountry[i].Country.Id).find(".label_check input").attr('checked', true);

            }
            $("#box_select_countries").css("display", "block");
            $('#messages').addClass('hide');
            $('.rows').removeClass('hover');
            $('.row_hide').addClass('hide');
            if ($('.rows').length > 3) {
                $('.col_method').css('width', '105px');
            }
            else {
                $('.col_method').css('width', '106px');
            }
            $('.list_row').jScrollPane({ animateScroll: true });
        } else {
            $("#box_select_countries").css("display", "none");
        }
    });

    //close countries box
    $('#fancybox-close').click(function () {
        $('#comfirm_blk').jqmShow();
    });
    $('#confirm_ok').click(function () {
        $('#comfirm_blk').jqmHide();
        $("#box_select_countries").css("display", "none");
    });

    $('#ddlrecurring').change(function () {
        if ($(this).val() == "None") {
            $('.list_recurring').addClass('hide');
        }
        if ($(this).val() == "Occurs each hour on these minutes") {
            $('.list_recurring').addClass('hide');
            $('#hour').removeClass('hide');
        }
        if ($(this).val() == "Occurs each day at these times") {
            $('.list_recurring').addClass('hide');
            $('#day').removeClass('hide');
        }
        if ($(this).val() == "Occurs each week on these days") {
            $('.list_recurring').addClass('hide');
            $('#week').removeClass('hide');
        }
        if ($(this).val() == "Occurs each month on these days") {
            $('.list_recurring').addClass('hide');
            $('#month').removeClass('hide');
        }
        if ($(this).val() == "Occurs every year on these dates") {
            $('.list_recurring').addClass('hide');
            $('#year').removeClass('hide');
        }
    });

    //    $('#add_minute').click(function () {
    //        var minute = $('#txt_minute').val();
    //        if (minute != "") {
    //            $('#minutes').append('<span class="icon_remove">:' + minute + '</span>');
    //            $('#txt_minute').val('');
    //        }
    //        $(".icon_remove").click(function () {
    //            $(this).remove();
    //        });
    //    });


    //add hour by click 
    $('#add_hour').click(function () {
        var hours = $('#txt_hour').val();
        if (hours != "") {
            $('#hours').append('<span class="icon_remove">' + hours + '</span>');
            $('#txt_hour').val('');
        }
        $(".icon_remove").click(function () {
            $(this).remove();
        });
    });


    //add day by click or bind data when edit
    $('#add_day').click(function () {
        var days = $('#txt_day').val();
        if (days != "") {
            $('#list_days').append('<span class="icon_remove">' + days + '</span>');
            $('#txt_day').val('');
        }
        $(".icon_remove").click(function () {
            $(this).remove();
        });
    });


    //add date by click or bind data when edit
    $('#add_date').click(function () {
        var dates = $('#txt_mmdd').val();
        if (dates != "") {
            $('#list_dates').append('<span class="icon_remove">' + dates + '</span>');
            $('#txt_mmdd').val('');
        }
        $(".icon_remove").click(function () {
            $(this).remove();
        });
    });

    $(".icon_remove").click(function () {
        $(this).remove();
    });
    $('div.rows').hide();
    $('input.text_input').keyup(function () {
        //alert('"' + $(this).val() + '"');
        if ($(this).val() == "") {
            $('label.label_check_ip').removeClass('c_ip_on');
            $('label.label_check_ip input#checkbox1').removeAttr('checked');
            $('label.label_check_ip input#checkbox1').attr('disabled', 'disabled');

        }
        else $('label.label_check_ip input#checkbox1').removeAttr('disabled');
    });

    $('.list_row').jScrollPane({ animateScroll: true });
    function buildMessageFlowCollection(messflowid) {
        if (messflowid == undefined) return;
        var messageflow = new Object();
        messageflow.messagebody = $("#mess_detail_" + messflowid).find(".textarea_enable").val();
        messageflow.messageflowtypeid = "1"; // Here messageflowtypeid is component //id(Win , Vote, Poll, Alert etc)
        var keywordids = new Array();
        $("#mess_detail_" + messflowid).find(".button_b").each(function () {
            if ($(this).attr("id") != "btKeywordTemp") {
                keywordids.push($(this).attr("value"));
            }
        });
        if (keywordids.length == 0) {
            keywordids.push("1");
        }
        messageflow.keywordids = keywordids  //Add keyword  , keyword is empty if no        //keyword is created for this message                  

        var arrcountry = messflowid.split("_");
        messageflow.countryid = arrcountry[0];  //countryid is the same as its country preference
        messageflow.languageid = arrcountry[1]; //languageid is the same as its country preference                      
        messageflow.mediaid = arrcountry[2]; //media is the same as its country preference
        return messageflow;
    }
    function validateMakeKeyword() {
        var ex = true;
        var optInKW = $("#txtKeywordOptIn").val();
        var optOutKW = $("#txtKeywordOptOut").val();
        if (optInKW == "" || optOutKW == "") {
            $('#errorMakekeyword').html("Opt-In and Opt-Out keywords must be entered.");
            $('#errorMakekeyword').css('color', '#ff5050');
            return false;
        }

        /* Look up if keyword is previously defined */

        var arrCountryId = $("#make_keyword_alert").attr("messflowid").split("_");
        var countryid = arrCountryId[0];
        var campaignid = $("#campaign_selection").find("option:selected").attr("id");

        $.ajax({
            url: gb_servicePath + "/keyword/lookup.json?name=" + optInKW + '&campaignid=' + campaignid + '&countryid=' + countryid,
            crossDomain: "true",
            type: "GET",
            async: false,
            "dataType": 'json',
            success: function (data) {
                if (data.ReturnData.length > 0) {
                    $('#errorMakekeyword').html(optInKW + " is already defined in the system. Please choose another keyword.");
                    $('#errorMakekeyword').css('color', '#ff5050');
                    ex = false;
                }
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/keyword/lookup.json");
                }
            }
        });

        $.ajax({
            url: gb_servicePath + "/keyword/lookup.json?name=" + optOutKW + '&campaignid=' + campaignid + '&countryid=' + countryid,
            crossDomain: "true",
            type: "GET",
            async: false,
            "dataType": 'json',
            success: function (data) {
                if (data.ReturnData.length > 0) {
                    $('#errorMakekeyword').html(optOutKW + " is already defined in the system. Please choose another keyword.");
                    $('#errorMakekeyword').css('color', '#ff5050');
                    ex = false;
                }
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/keyword/lookup.json");
                }
            }
        });

        /*
        $("#tbl_new_userOptIn").find(".messagesflowtype").each(function () {
        if ($(this).find(".countable").val() == "") {
        $('#errorMakekeyword').html("All field should be entered ");
        $('#errorMakekeyword').css('color', '#ff5050');
        ex = false;
        }
        });
        $("#tbl_new_userOptOut").find(".messagesflowtype").each(function () {
        if ($(this).find(".countable").val() == "") {
        $('#errorMakekeyword').html("All field should be entered ");
        $('#errorMakekeyword').css('color', '#ff5050');
        ex = false;
        }
        }); */
        return ex;
    }
    function buildKeyWorldCollection(compId) {
        var keyword = new Object();
        if (compId == 6) {
            keyword.name = $("#txtKeywordOptIn").val();
        } else {
            keyword.name = $("#txtKeywordOptOut").val();
        };

        keyword.componentid = compId; // Here function is component for alert/Hub
        var audience = new Array();
        audience.push($("#audience_selection").find("option:selected").attr("id"));
        keyword.grouplist = audience;
        keyword.campaignid = $("#campaign_selection").find("option:selected").attr("id"); //campaign id is the same as the campaign id of the alert collection
        var arrCountryId = $("#make_keyword_alert").attr("messflowid").split("_");
        keyword.countryid = arrCountryId[0];  //countryid is the same as it’s parent message flow
        keyword.languageid = arrCountryId[1]; //languageid is the same as it’s parent message flow
        keyword.mediaid = arrCountryId[2]; //media is the same as it’s parent message flow 
        var messagelist = new Array();
        if (compId == 6) {
            $("#tbl_new_userOptIn").find(".messagesflowtype").each(function () {
                if ($(this).find(".countable").val() != "") {
                    var message1 = new Object();
                    message1.messageflowtypeid = $(this).attr("value"); // message type id
                    message1.messagebody = $(this).find(".countable").val(); // message body
                    messagelist.push(message1); //add message1 to keyword object    
                }
            });
        }
        if (compId == 7) {
            $("#tbl_new_userOptOut").find(".messagesflowtype").each(function () {
                if ($(this).find(".countable").val() != "") {
                    var message1 = new Object();
                    message1.messageflowtypeid = $(this).attr("value"); // message type id
                    message1.messagebody = $(this).find(".countable").val(); // message body
                    messagelist.push(message1); //add message1 to keyword object    
                }
            });
        }
        keyword.messagelist = messagelist;
        return keyword;
    }

    function buildAlertCollection() {
        var alertcollection = new Object();
        alertcollection.name = $("#txtName").val();
        alertcollection.campaignid = $("#campaign_selection").find("option:selected").attr("id");
        //alertcollection.campaignid = "1";
        //alertcollection.starttime = $("#start_date").val() + " " + $("#start_time").val();
        //alertcollection.endtime = $("#end_date").val() + " " + $("#end_time").val();
        var arrstarttime = $("#start_date").val().split("/");
        alertcollection.starttime = arrstarttime[2] + "-" + arrstarttime[0] + "-" + arrstarttime[1] + " " + $("#start_time").val();
        var arrendtime = $("#end_date").val().split("/");
        alertcollection.endtime = arrendtime[2] + "-" + arrendtime[0] + "-" + arrendtime[1] + " " + $("#end_time").val();
        alertcollection.isrecurring = true;
        if ($(".label_check_ip").hasClass("c_ip_on")) {
            alertcollection.isactive = true;
        } else {
            alertcollection.isactive = false;
        }
        //alertcollection.userid = userId;
        alertcollection.createdby = userId;
        alertcollection.approvalstatusid = 1;
        alertcollection.componentid = 1;
        //
        var arrAudienceId = new Array();
        $("#list_audience").find(".list_count").each(function () {
            if ($(this).find(".label_check").hasClass("c_on")) {
                arrAudienceId.push($(this).attr("id"));
            }

        });
        if (arrAudienceId.length == 0) {
            $('#error').html("Audiences should be selected ");
            return null;
        }
        alertcollection.audienceids = arrAudienceId;
        alertcollection.frequency = new Array();
        //  alert($("#ddlrecurring").val());
        switch ($("#ddlrecurring").val()) {
            case "None":
                alertcollection.isrecurring = false;
                break;
            case "Occurs each hour on these minutes":
                var frequency = new Object();
                frequency.timeunitid = "2";
                frequency.timeunitvalue = "1";
                alertcollection.frequency.push(frequency);

                $("#minutes").find("span").each(function () {
                    var frequency = new Object();
                    frequency.timeunitid = "1";
                    frequency.timeunitvalue = $(this).html().split(":")[1];
                    alertcollection.frequency.push(frequency);
                });
                break;
            case "Occurs each day at these times":
                var frequency = new Object();
                frequency.timeunitid = "3";
                frequency.timeunitvalue = "1";
                alertcollection.frequency.push(frequency);

                var arrH = new Array();
                var arrM = new Array();
                $("#hours").find("span").each(function () {
                    var str = $(this).html().split(":");
                    arrH.push(str[0]);
                    arrM.push(str[1]);
                });
                for (var i = 0; i < arrH.length; i++) {
                    var frequency = new Object();
                    frequency.timeunitid = "1";
                    frequency.timeunitvalue = parseInt(arrH[i]) * 60 + parseInt(arrM[i]);
                    alertcollection.frequency.push(frequency);
                }

                break;
            case "Occurs each week on these days":
                var frequency = new Object();
                frequency.timeunitid = "4";
                frequency.timeunitvalue = "1";
                alertcollection.frequency.push(frequency);

                $("#week").find(".label_check").each(function () {
                    if ($(this).hasClass("c_on")) {
                        var frequency = new Object();
                        frequency.timeunitid = "3";
                        frequency.timeunitvalue = $(this).attr("value");
                        alertcollection.frequency.push(frequency);
                    }
                });

                break;
            case "Occurs each month on these days":
                var frequency = new Object();
                frequency.timeunitid = "5";
                frequency.timeunitvalue = "1";
                alertcollection.frequency.push(frequency);
                $("#list_days").find("span").each(function () {
                    var frequency = new Object();
                    frequency.timeunitid = "3";
                    frequency.timeunitvalue = $(this).html();
                    alertcollection.frequency.push(frequency);
                });
                break;
            case "Occurs every year on these dates":
                var frequency = new Object();
                frequency.timeunitid = "6";
                frequency.timeunitvalue = "1";
                alertcollection.frequency.push(frequency);
                $("#list_dates").find("span").each(function () {
                    var str = $(this).html().split("/");

                    var frequency = new Object();
                    frequency.timeunitid = "3";
                    var tempdt = new Date((new Date()).getFullYear(), str[0] - 1, str[1]);
                    frequency.timeunitvalue = getDOY(tempdt).toString();
                    alertcollection.frequency.push(frequency);
                });
                break;
        }
        if (alertcollection.frequency.length == 0 && alertcollection.isrecurring == true) {
            $('#error').html("Frequency times should be entered ");
            $('#error').css('color', '#ff5050');
            return null;
        }


        alertcollection.messageflowids = new Array();
        alertcollection.countrymediapreference = new Array();
        var missingMessagesFlow = false;
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                var o = jQuery.parseJSON($(this).attr("data"));
                for (var i = 0; i < o.Language.length; i++) {
                    if (o.Language[i].selected == true) {
                        var medias = o.Language[i].Media;
                        for (var j = 0; j < medias.length; j++) {
                            if (medias[j].selected == true) {
                                var pref = new Object();
                                var ctryPref = new Object();
                                ctryPref.countryid = o.Country.Id
                                ctryPref.id = o.Language[i].CountryPreId;
                                ctryPref.languageid = o.Language[i].Id;
                                ctryPref.timezoneid = o.Timezone.Id;
                                pref.countrypreference = ctryPref;
                                pref.mediaid = medias[j].Id;
                                alertcollection.countrymediapreference.push(pref);
                                if (arrMessagesFlows[o.Country.Id + "_" + o.Language[i].Id + "_" + medias[j].Id] != undefined) {
                                    alertcollection.messageflowids.push(arrMessagesFlows[o.Country.Id + "_" + o.Language[i].Id + "_" + medias[j].Id].Id);
                                } else {
                                    // alertcollection.messageflowids.push("1");
                                    $('#error').html("Message for each (country,language,method) should be entered ");
                                    $('#error').css('color', '#ff5050');
                                    missingMessagesFlow = true;
                                    return null;
                                }
                            }
                        }
                    }
                }
            }
        });

        if (missingMessagesFlow) {
            return null;
        } else {
            return alertcollection;
        }
    }


    $("#btnSaveKeyWord").click(function () {

        if ($("#btnSaveKeyWord .cus_button_mid").html() == "Update") {
            var keyword = new Object();
            keyword.id = $("#make_keyword_alert").attr("keywordid");
            var messagelist = new Array();
            var compId = $("#make_keyword_alert").attr("compid");
            keyword.name = $('#make_keyword_alert').attr("keywordname");
            if (compId == 6) {
                $("#tbl_new_userOptIn").find(".messagesflowtype").each(function () {
                    if ($(this).find(".countable").val() != "") {
                        var message1 = new Object();
                        message1.messageflowtypeid = $(this).attr("value"); // message type id
                        message1.messagebody = $(this).find(".countable").val(); // message body
                        messagelist.push(message1); //add message1 to keyword object    
                    }
                });
            }
            if (compId == 7) {
                $("#tbl_new_userOptOut").find(".messagesflowtype").each(function () {

                    if ($(this).find(".countable").val() != "") {
                        var message1 = new Object();
                        message1.messageflowtypeid = $(this).attr("value"); // message type id
                        message1.messagebody = $(this).find(".countable").val(); // message body
                        messagelist.push(message1); //add message1 to keyword object    
                    }
                });
            }
            keyword.userid = userId;
            keyword.messagelist = messagelist;

            $.ajax({
                url: gb_servicePath + 'Keyword/Update.json',
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(keyword),
                "dataType": 'json',
                success: function (data) {
                    if (json1.StatusCode == 200) {

                    }
                }
            });
            $('#make_keyword_alert').jqmHide();
            return true;

        }
        else {
            if (validateMakeKeyword()) {
                $('#make_keyword_alert').jqmHide();
                $.ajax({
                    url: gb_servicePath + "/keyword/create.json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(buildKeyWorldCollection(6)),
                    "dataType": 'json',
                    success: function (data) {
                        // alert('ok');
                        //now add new keyword to messages flow
                        var o = $("#btKeywordTemp").clone();
                        /*  $(o).attr("value", data.Id);
                        $(o).find(".key_button_mid").html($("#txtKeyword").val());*/
                        $(o).attr("value", data.ReturnData.Id);
                        $(o).find(".key_button_mid").html(data.ReturnData.Name);
                        $(o).find(".key_button_mid").attr("id", data.ReturnData.Id);
                        $(o).css("display", "block");
                        $(o).attr("id", "btKeyword" + data.ReturnData.Id);
                        $("#mess_detail_" + $("#make_keyword_alert").attr("messflowid")).find(".keywordcollection").append(o);
                        $(o).find(".key_button_right").click(function () {
                            if (!$(this).parent().hasClass("disable")) {
                                removeKeyword($(this).prev().attr("id"), userId, $("#make_keyword_alert").attr("messflowid"));
                                $(this).parent().parent().remove();
                            }
                        });
                        $(".key_button_mid").click(function () {
                            var idkeyword = $(this).attr("id");
                            //alert(idkeyword);
                        });
                    },
                    error: function (jqXHR, textStatus) {
                        if (isBug) {
                            alert("Error in GEMAPI/keyword/create.json");
                        }
                    }
                });

                $.ajax({
                    url: gb_servicePath + "/keyword/create.json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(buildKeyWorldCollection(7)),
                    "dataType": 'json',
                    success: function (data) {
                        // alert('ok');
                        //now add new keyword to messages flow
                        var o = $("#btKeywordTemp").clone();
                        /*  $(o).attr("value", data.Id);
                        $(o).find(".key_button_mid").html($("#txtKeyword").val());*/
                        $(o).attr("value", data.ReturnData.Id);
                        $(o).find(".key_button_mid").html(data.ReturnData.Name);
                        $(o).find(".key_button_mid").attr("id", data.ReturnData.Id);
                        $(o).css("display", "block");
                        $(o).attr("id", "btKeyword" + data.ReturnData.Id);
                        $("#mess_detail_" + $("#make_keyword_alert").attr("messflowid")).find(".keywordcollection").append(o);
                        $(o).find(".key_button_right").click(function () {
                            if (!$(this).parent().hasClass("disable")) {
                                removeKeyword($(this).prev().attr("id"), userId, $("#make_keyword_alert").attr("messflowid"));
                                $(this).parent().parent().remove();
                            }
                        });
                        //$(o).attr("keywordidlist", keywordidlist);
                        $(".key_button_mid").click(function () {
                            var idkeyword = $(this).attr("id");
                            //alert(idkeyword);
                        });

                    },
                    error: function (jqXHR, textStatus) {
                        if (isBug) {
                            alert("Error in GEMAPI/keyword/create.json");
                        }
                    }
                });
            }
        }

    });
    //convert to unit timestamp
    function toTimestamp(strDate) {
        var datum = Date.parse(strDate);
        return datum / 1000;
    }

    function validateForm() {
        var ex = true;
        var name = $("#txtName").val();
        var senddate = $("#start_date").val();
        var enddate = $("#end_date").val();
        var sendtime = $("#start_time").val();
        var endtime = $("#end_time").val();
        var recurring = $('#ddlrecurring').attr('id');

        if (recurring != "1") {
            if (recurring == '2') {
                if ($('#minutes').html = "") {
                    $('#error').css('color', '#ff5050');
                    $('#error').html("Minutes should be entered");
                    $('#title_rec').css('color', '#ff5050');
                    $('#error').css('color', '#ff5050');
                    ex = false;
                }
            }
        }

        var start_unit = toTimestamp(senddate + ' ' + $('#start_time').val());
        var end_unit = toTimestamp(enddate + ' ' + $('#end_time').val());



        if (senddate == "" || sendtime == "    :") {
            $('#error').html("Start date and time should be entered");
            $('#startdate').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        } else {
            $('#startdate').css('color', '#595959');
        }
        if (enddate == "" || endtime == "    :") {
            $('#error').html("End date and time should be entered");
            $('#enddate').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        } else {
            if (start_unit > end_unit) {
                $('#error').html("End date must be greater than start date");
                $('#enddate').css('color', '#ff5050');
                $('#startdate').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                return;
            }
            $('#enddate').css('color', '#595959');
        }
        if (arrCurrentCountry.length == 0) {
            $('#error').html("Please select at least one country");
            $('#rowCountries table').css('border', '1px solid #ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        //check Countries Language and Method
        if (arrCurrentCountry.length > 0) {
            var lang = 0;
            var media = 0;
            for (var j = 0; j < arrCurrentCountry.length; j++) {
                //lang = lang + arrCurrentCountry[j].Language.length; //get All language
                for (var l = 0; l < arrCurrentCountry[j].Language.length; l++) {
                    if (arrCurrentCountry[j].Language[l].selected) {
                        lang++;
                        for (var k = 0; k < arrCurrentCountry[j].Language[l].Media.length; k++) {
                            //media = media + arrCurrentCountry[j].Language[k].Media.length; //get All media
                            if (arrCurrentCountry[j].Language[l].Media[k].selected) {
                                media++;
                            }
                        }
                    }
                }

            }
            if (media == 0) {
                $('#error').html("Please select at at least one delivery method");
                $('#rowCountries .method').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
            if (lang == 0) {
                $('#error').html("Please select at at least one language for selected countries");
                $('#rowCountries .lang').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }

        if (name == "") {

            $('#error').html("Alert name should be entered");
            $('#title_name').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }

        var counter1 = 0;
        if ($("#ddlrecurring").val() == "Occurs each day at these times") {
            $("#hours").find("span").each(function () {
                counter1++
            });
            if (counter1 == 0) {
                $('#error').html("Required: Occurs each day at these times");
                $('#title_name').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }

        var counter2 = 0;
        if ($("#ddlrecurring").val() == "Occurs each week on these days") {
            $("#week").find(".label_check").each(function () {
                if ($(this).hasClass("c_on")) {
                    var hasDate = $(this).attr("value");
                    counter2++

                }
            });
            if (counter2 == 0) {
                $('#error').html("Required: Occurs each week on these days");
                $('#title_name').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }

        var counter3 = 0;
        if ($("#ddlrecurring").val() == "Occurs each month on these days") {
            $("#list_days").find("span").each(function () {
                var valu = $(this).html();
                counter3++
            });
            if (counter3 == 0) {
                $('#error').html("Required: Occurs each month on these days");
                $('#title_name').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }

        var counter4 = 0;
        if ($("#ddlrecurring").val() == "Occurs every year on these dates") {
            $("#list_dates").find("span").each(function () {
                var str = $(this).html().split("/");
                var tempdt = new Date((new Date()).getFullYear(), str[0] - 1, str[1]);
                counter4++
            });
            if (counter4 == 0) {
                $('#error').html("Required: Occurs every year on these dates");
                $('#title_name').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }










        //        else {
        //            checkUnique(name, $('select#sl_campaign option:selected').attr('id'));
        //            if ($('#error').html() == 'Alert with this name already exists. Please choose another name.') {
        //                ex = false;
        //            }
        //        }

        return ex;
    }
    function checkUnique(name, campaignid) {
        //alertcolletion/list/summary.json?name=<alert name>&campaignid= <id of campaign the alert is for>
        //alert(name +"-" +campaignid);
        var ex = new Object();
        $.getJSON(gb_servicePath + 'alertcollection/list/summary.json?name=' + name + '&campaignid=' + campaignid,
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData.length > 0) {
                            if (getURLParameter("id").toString() != "null") {// if action is edit
                                if (getURLParameter("id").toString() == json1.ReturnData.Id.toString()) {
                                    $('#error').html("Alert with this name already exists. Please choose another name.");
                                    $('#title_name').css('color', '#ff5050');
                                    $('#error').css('color', '#ff5050');
                                }
                            }
                            else {// if action is create new
                                $('#error').html("Alert with this name already exists. Please choose another name.");
                                $('#title_name').css('color', '#ff5050');
                                $('#error').css('color', '#ff5050');
                            }
                        }
                    }
                    else {
                        if (isBug) {
                            alert('Error in alertcollection/list/summary.json');
                        }
                    }
                });
    }
    $("#txtName").keypress(function () {
        $('#error').html('');
        $('#title_name').css('color', '#595959');
    });
    $("#start_date").keypress(function () {
        $('#error').html('');
        $('#startdate').css('color', '#595959');
    });
    $("#end_date").keypress(function () {
        $('#error').html('');
        $('#startdate').css('color', '#595959');
        $('#enddate').css('color', '#595959');
    });
    $("#start_time").keypress(function () {

        $('#error').html('');
        $('#startdate').css('color', '#595959');
    });
    $("#end_time").keypress(function () {
        $('#error').html('');
        $('#startdate').css('color', '#595959');
        $('#enddate').css('color', '#595959');
    });
    $("#btnSaveAsDraft").click(function () {
        if (validateForm()) {
            $.getJSON(gb_servicePath + 'alertcollection/list/summary.json?name=' + $("#txtName").val() + '&campaignid=' + $('select#sl_campaign option:selected').attr('id'),
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData.length > 0) {
                            if (getURLParameter("id").toString() != "null") {// if action is edit
                                if (getURLParameter("id").toString() == json1.ReturnData.Id.toString()) {
                                    $('#error').html("Alert with this name already exists. Please choose another name.");
                                    $('#title_name').css('color', '#ff5050');
                                    $('#error').css('color', '#ff5050');
                                }
                            }
                            else {// if action is create new
                                $('#error').html("Alert with this name already exists. Please choose another name.");
                                $('#title_name').css('color', '#ff5050');
                                $('#error').css('color', '#ff5050');
                            }
                        }
                        else {
                            var alertcollection = buildAlertCollection();
                            alertcollection.approvalstatusid = 2;
                            $.ajax({
                                url: gb_servicePath + "/alertcollection/create.json",
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(alertcollection),
                                "dataType": 'json',
                                success: function (data) {
                                    window.location.href = '../Source/AlertLibrary';
                                },
                                error: function (jqXHR, textStatus) {
                                    if (isBug) {
                                        //alert("Error in GEMAPI/alertcollection/create.json");
                                    }
                                }

                            });
                        }
                    }
                    else {
                        if (isBug) {
                            alert('Error in alertcollection/list/summary.json');
                        }
                    }
                });

        }
    });
    $("#btnSave").click(function () {

        if (validateForm()) {
            if ($("#btnSave").find(".cus_button_mid").html() == "Update") {
                // update alert 
                var alertcollection = buildAlertCollection();
                $.ajax({
                    url: gb_servicePath + "/alertcollection/update/" + alertInstance.Id + ".json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(alertcollection),
                    "dataType": 'json',
                    success: function (data) {
                        window.location.href = '../Source/AlertLibrary';
                    },
                    error: function (jqXHR, textStatus) {

                        if (isBug) {
                            $("#box_alert").find(".text_confirm").html("Error when update alert");
                            $("#box_alert").jqmShow();
                        }
                    }

                });
                return true;
            }

            $.getJSON(gb_servicePath + 'alertcollection/list/summary.json?name=' + $("#txtName").val() + '&campaignid=' + $('select#sl_campaign option:selected').attr('id'),
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData.length > 0) {
                            if (getURLParameter("id").toString() != "null") {// if action is edit
                                if (getURLParameter("id").toString() == json1.ReturnData.Id.toString()) {
                                    $('#error').html("Alert with this name already exists. Please choose another name.");
                                    $('#title_name').css('color', '#ff5050');
                                    $('#error').css('color', '#ff5050');
                                    return false;
                                }
                            }
                            else {// if action is create new
                                $('#error').html("Alert with this name already exists. Please choose another name.");
                                $('#title_name').css('color', '#ff5050');
                                $('#error').css('color', '#ff5050');
                                return false;
                            }
                        }

                        var alertcollection = buildAlertCollection();


                        if (alertcollection == null) return;
                        if ($("#btnSave").find(".cus_button_mid").html() == "Save") {
                            $.ajax({
                                url: gb_servicePath + "/alertcollection/create.json",
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(alertcollection),
                                "dataType": 'json',
                                success: function (data) {
                                    window.location.href = '../Source/AlertLibrary';
                                },
                                error: function (jqXHR, textStatus) {
                                    if (isBug) {
                                        //alert("Error in GEMAPI/alertcollection/create.json");
                                    }
                                }

                            });
                        }

                    }
                    else {
                        if (isBug) {
                            alert('Error in alertcollection/list/summary.json');
                        }
                    }
                });


        }
        else {
            return false;
        }
    });

    //for country box

    //close messages box
    $('#messages-close').click(
        function () {
            jConfirm('Do you want to close this dialog?', 'Confirmation Dialog', function (r) {
                if (r) {
                    $('.edit_disable').css('display', 'block');
                    $('.edit_enable').css('display', 'none');
                    $('.mess_detail textarea').attr('disabled', 'disabled');
                    $('.mess_detail textarea').removeClass('textarea_enable');
                    $('.itemfilter').show();
                    $('.btn_unleashed').hide();
                    $('.btn_freetix').hide();
                    $('#btn_SaveMessage').addClass('hide');
                    $('#btn_Cancel').addClass('hide');
                    $('#btn_Edit').removeClass('hide');
                    $(".btparent").addClass("disable");
                    $(".btparent").removeClass("width_close");

                    $('#messages').addClass('hide');
                    $('.rows').removeClass('hover');
                    $('.row_hide').addClass('hide');
                    if ($('.rows').length > 3) {
                        $('.col_method').css('width', '105px');
                    }
                    else {
                        $('.col_method').css('width', '106px');
                    }
                    $('.list_row').jScrollPane({ animateScroll: true });
                } else {
                    //do anything else
                }
            });
        }
    );
    //Cancel box messages
    $('#btn_Cancel').click(function () {
        $('.edit_disable').css('display', 'block');
        $('.edit_enable').css('display', 'none');
        $('.mess_detail textarea').attr('disabled', 'disabled');
        $('.mess_detail textarea').removeClass('textarea_enable');
        $('.itemfilter').show();
        $('.btn_unleashed').hide();
        $('.btn_freetix').hide();
        $('#btn_SaveMessage').addClass('hide');
        $('#btn_Cancel').addClass('hide');
        $('#btn_Edit').removeClass('hide');
        $(".btparent").addClass("disable");
        $(".btparent").removeClass("width_close");

        $('#messages').addClass('hide');
        $('.rows').removeClass('hover');
        $('.row_hide').addClass('hide');
        if ($('.rows').length > 3) {
            $('.col_method').css('width', '105px');
        }
        else {
            $('.col_method').css('width', '106px');
        }
        $('.list_row').jScrollPane({ animateScroll: true });
    });
    //Save box messages
    $('#btn_SaveMessage').click(function () {
        //        jConfirm('Do you want to save messages?', 'Confirmation Dialog', function (r) {
        //            if (r) {
        //call save messages function
        var url;
        if ($("#btnSave").find(".cus_button_mid").html() == "Save") {
            url = "/messageflow/create.json";
        }

        $("#messflows").find(".mess_detail").each(function () {
            if ($(this).attr("id") != "mess_detail_temp") {
                var flowid = $(this).attr("messflowid");
                if ($("#btnSave").find(".cus_button_mid").html() == "Update") {
                    iD = $("#mess_detail_" + flowid).find(".textarea_enable").attr("instanceid");
                    url = "/messageflow/update/" + iD + ".json";
                }



                if (flowid != undefined) {
                    $.ajax({
                        url: gb_servicePath + url,
                        crossDomain: "true",
                        type: "POST",
                        contentType: 'application/json; charset=utf-8',
                        traditional: true,
                        data: JSON.stringify(buildMessageFlowCollection(flowid)),
                        "dataType": 'json',
                        success: function (data) {

                            if ($("#btnSave").find(".cus_button_mid").html() != "Update") {
                                var oMess = new Object();

                                oMess.Id = data.ReturnData.Id;
                                oMess.countryId = data.ReturnData.Country.Id;
                                oMess.mediaId = data.ReturnData.Media.Id;
                                oMess.languageId = data.ReturnData.Language.Id;

                                var messfid = oMess.countryId + "_" + oMess.languageId + "_" + oMess.mediaId;
                                var messageflow = new Object();
                                messageflow.messagebody = $("#mess_detail_" + messfid).find("textarea").val();
                                messageflow.messageflowtypeid = "1"; // Here messageflowtypeid is component //id(Vote, Poll, Alert etc)

                                var keywordids = new Array();
                                var keywordvalues = new Array();
                                $("#mess_detail_" + messfid).find(".button_b").each(function () {
                                    if ($(this).attr("id") != "btKeywordTemp") {
                                        keywordids.push($(this).attr("value"));
                                        keywordvalues.push($(this).find(".key_button_mid").html());
                                    }
                                });

                                if (keywordids.length == 0) {
                                    keywordids.push("1");
                                }

                                oMess.messagesBody = messageflow.messagebody;
                                // oMess.messageflowType = { Id: val.MessageflowType.Id, Name: val.MessageflowType.Name };
                                // oMess.Name = val.Name;
                                oMess.keywordlist = keywordids;
                                oMess.keywordvalues = keywordvalues;
                                arrMessagesFlows[messfid] = oMess;
                            }
                            else {
                                //
                                $("#messflows").find(".mess_detail").each(function (val) {

                                    if ($(this).attr('id') != "mess_detail_temp") {
                                        var messfid = $(this).attr("messflowid");
                                        //bind messagesbody
                                        arrMessagesFlows[messfid].messagesBody = $(this).find("textarea").val();
                                        //bind new keywordlist
                                    }
                                });

                            }
                            $('.edit_disable').css('display', 'block');
                            $('.edit_enable').css('display', 'none');
                            $('.mess_detail textarea').attr('disabled', 'disabled');
                            $('.mess_detail textarea').removeClass('textarea_enable');
                            $('.itemfilter').show();
                            $('.btn_unleashed').hide();
                            $('.btn_freetix').hide();
                            $('#btn_SaveMessage').addClass('hide');
                            $('#btn_Cancel').addClass('hide');
                            $('#btn_Edit').removeClass('hide');
                            $(".btparent").addClass("disable");
                            $(".btparent").removeClass("width_close");

                            $('#messages').addClass('hide');
                            $('.row_hide').addClass('hide');
                            $('.rows').removeClass("hover");
                            $('.list_row').jScrollPane({ animateScroll: true });
                            //alert('ok');
                            //jAlert('Save messages success', 'Alert Dialog');
                            $('#error_mess').css('display', 'none');
                        },
                        error: function (jqXHR, textStatus) {
                            $('#error_mess').css('display', 'block');
                            $('#error_mess').html('Messages should be entered');
                            //jAlert('Save messages false', 'Alert Dialog');
                            //alert("Error in GEMAPI/keyword/create.json");
                        }
                    });
                }
            }
        });
        //            } else {
        //                //do anything else
        //            }
        //        });
    });
});
